const fs = require('fs');
const path = require('path');
const HttpServer = require('./src/HttpServer');
const WebSocketServer = require('./src/WebSocketServer');
const MessageHandler = require('./src/MessageHandler');
const KeyboardController = require('./src/KeyboardController');
const ScreenshotCapture = require('./src/ScreenshotCapture');

class PPTRemoteServer {
  constructor() {
    this.config = this.loadConfig();
    this.httpServer = null;
    this.wsServer = null;
    this.messageHandler = null;
    this.keyboardController = null;
    this.screenshotCapture = null;
    this.isRunning = false;
  }

  // 加载配置
  loadConfig() {
    try {
      const configPath = path.join(__dirname, 'config.json');
      const configData = fs.readFileSync(configPath, 'utf8');
      return JSON.parse(configData);
    } catch (error) {
      console.warn('加载配置文件失败，使用默认配置');
      return {
        port: 7663,
        fallbackPorts: [7664, 7665],
        screenshot: {
          quality: 75,
          maxWidth: 800,
          captureDelay: 300
        },
        websocket: {
          maxConnections: 20,
          pingInterval: 30000
        }
      };
    }
  }

  // 启动服务器
  async start() {
    try {
      console.log('正在启动PPT远程控制服务器...\n');

      // 尝试启动HTTP和WebSocket服务器
      const port = await this.startServers();

      // 初始化控制器
      this.keyboardController = new KeyboardController();
      this.screenshotCapture = new ScreenshotCapture(this.config.screenshot);

      // 设置消息处理
      this.setupMessageHandling();

      // 启动心跳检测
      this.wsServer.startHeartbeat(this.config.websocket.pingInterval);

      this.isRunning = true;
      console.log('\n服务器启动成功！');
      console.log('请在手机浏览器中访问上面显示的地址\n');

    } catch (error) {
      console.error('启动服务器失败:', error);
      process.exit(1);
    }
  }

  // 启动HTTP和WebSocket服务器
  async startServers() {
    const ports = [this.config.port, ...this.config.fallbackPorts];
    
    for (const port of ports) {
      let httpServer = null;
      let wsServer = null;
      
      try {
        // 启动HTTP服务器
        httpServer = new HttpServer(port);
        await httpServer.start();

        // 将WebSocket服务器附加到HTTP服务器上
        wsServer = new WebSocketServer(httpServer, this.config.websocket.maxConnections);
        await wsServer.start();

        // 两个服务器都启动成功，保存引用
        this.httpServer = httpServer;
        this.wsServer = wsServer;

        // 初始化消息处理器
        this.messageHandler = new MessageHandler(this.wsServer);

        return port;

      } catch (error) {
        // 如果启动失败，清理已启动的服务器
        if (httpServer && httpServer.server) {
          try {
            httpServer.stop();
          } catch (e) {
            // 忽略清理错误
          }
        }
        if (wsServer && wsServer.wss) {
          try {
            wsServer.stop();
          } catch (e) {
            // 忽略清理错误
          }
        }

        if (error.code === 'EADDRINUSE') {
          console.log(`端口 ${port} 已被占用，尝试下一个端口...`);
          continue;
        }
        throw error;
      }
    }

    throw new Error('所有端口都已被占用');
  }

  // 设置消息处理
  setupMessageHandling() {
    // 监听WebSocket消息
    this.wsServer.on('message', (message, client) => {
      this.messageHandler.handleMessage(message, client);
    });

    // 监听控制指令
    this.messageHandler.on('control', async (action) => {
      await this.handleControlAction(action);
    });

    // 监听连接事件
    this.wsServer.on('connection', (client) => {
      console.log(`当前连接数: ${this.wsServer.getConnectionCount()}`);
    });

    // 监听断开事件
    this.wsServer.on('disconnect', (client) => {
      console.log(`当前连接数: ${this.wsServer.getConnectionCount()}`);
    });
  }

  // 处理控制动作
  async handleControlAction(action) {
    const startTime = Date.now();

    try {
      // 映射动作到按键
      const key = action === 'next' ? 'right' : 'left';

      // 发送按键（使用增强方法）
      const success = await this.keyboardController.sendKeyEnhanced(key);

      if (!success) {
        this.messageHandler.broadcastError('按键发送失败', 'KEY_SEND_FAILED');
        return;
      }

      // 等待PPT动画完成
      await new Promise(resolve => setTimeout(resolve, this.config.screenshot.captureDelay));

      // 更新幻灯片索引
      const currentIndex = this.messageHandler.getCurrentSlideIndex();
      const newIndex = action === 'next' ? currentIndex + 1 : Math.max(1, currentIndex - 1);
      this.messageHandler.setCurrentSlideIndex(newIndex);

      // 捕获并发送截图
      await this.captureAndSendScreenshot(newIndex);

      const totalTime = Date.now() - startTime;
      console.log(`控制动作完成 (总时间: ${totalTime}ms)\n`);

    } catch (error) {
      console.error('处理控制动作失败:', error);
      this.messageHandler.broadcastError('处理控制指令失败', 'CONTROL_FAILED');
    }
  }

  // 捕获并发送截图
  async captureAndSendScreenshot(slideIndex) {
    try {
      const imageData = await this.screenshotCapture.captureAndCompress();
      
      if (imageData) {
        this.messageHandler.sendSlideUpdate(slideIndex, imageData);
      } else {
        console.warn('截图捕获失败，跳过发送');
      }

    } catch (error) {
      console.error('捕获截图失败:', error);
    }
  }

  // 停止服务器
  stop() {
    console.log('\n正在关闭服务器...');

    if (this.wsServer) {
      this.wsServer.stop();
    }

    if (this.httpServer) {
      this.httpServer.stop();
    }

    this.isRunning = false;
    console.log('服务器已关闭');
  }
}

// 创建并启动服务器
const server = new PPTRemoteServer();

// 处理退出信号
process.on('SIGINT', () => {
  console.log('\n收到退出信号...');
  server.stop();
  process.exit(0);
});

process.on('SIGTERM', () => {
  server.stop();
  process.exit(0);
});

// 启动服务器
server.start().catch(error => {
  console.error('启动失败:', error);
  process.exit(1);
});

module.exports = PPTRemoteServer;
